TOOL.Category		= "Construction"
TOOL.Name			= "#Force Dynamite"
TOOL.Command		= nil
TOOL.ConfigName		= ""


TOOL.ClientConVar[ "group" ] = 1		// Current group
TOOL.ClientConVar[ "force" ] = 2000
TOOL.ClientConVar[ "recoil" ] = 1
TOOL.ClientConVar[ "reload" ] = 5
TOOL.ClientConVar[ "bangradius" ] = 256
TOOL.ClientConVar[ "model" ] = "models/dav0r/tnt/tnt.mdl"
TOOL.ClientConVar[ "effect" ] = "Explosion"
TOOL.ClientConVar[ "explodeoncontact" ] = "0"

cleanup.Register( "forcedynamite" )

if (SERVER) then
  CreateConVar('sbox_maxforcedynamite',10)
end

// Add Default Language translation (saves adding it to the txt files)
if ( CLIENT ) then

	language.Add( "Tool_forcedynamite_name", "Force Dynamite" )
	language.Add( "Tool_forcedynamite_desc", "Dynamite that applies force without damage to props in line of sight" )
	language.Add( "Tool_forcedynamite_0", "Click somewhere to spawn force dynamite. Click on an existing dynamite to change it." )

	language.Add( "Undone_forcedynamite", "Undone Force Dynamite" )
	language.Add( "Cleanup_forcedynamite", "Force Dynamite" )
	language.Add( "Cleaned_forcedynamite", "Cleaned up all Force Dynamite" )

end



function TOOL:LeftClick( trace )

	--Msg("Left clicked")
	if (!trace.HitPos) then return false end
	if (trace.Entity:IsPlayer()) then return false end
	
	if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
	
	if ( CLIENT ) then return true end
	
	// Get client's CVars
	local ply = self:GetOwner()
	local force			= self:GetClientNumber( "force" )
	local recoil		= self:GetClientNumber( "recoil" )
	local reload		= self:GetClientNumber( "reload" )
	local model			=self:GetClientInfo("model")
	local bangradius	=self:GetClientNumber("bangradius")
	local effect			= self:GetClientInfo( "effect" )
	local explodeoncontact = self:GetClientNumber("explodeoncontact") == 1
	
	local group		= self:GetClientNumber( "group" )

    --Msg("Here")

	if (not util.IsValidModel(model)) then return false end
	if (not util.IsValidProp(model)) then return false end

    // We shot an existing cannon - just change its values
	if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_forcedynamite" && trace.Entity:GetTable():GetPlayer() == ply ) then

		trace.Entity:GetTable():Setup( force, model,recoil, reload, bangradius, effect, explodeoncontact)
		return true

	end
	
	if !ply:CheckLimit('forcedynamite') then return end

	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	local cannon = MakeFDynamite( ply, trace.HitPos, Ang, group, force, model, recoil, reload, bangradius, effect, explodeoncontact)
	
	local min = cannon:OBBMins()
	cannon:SetPos( trace.HitPos - trace.HitNormal * min.z )

    local const, nocollide

	// Don't weld to world
	if ( trace.Entity:IsValid() ) then
		const = constraint.Weld( cannon, trace.Entity, 0, trace.PhysicsBone, 0, systemmanager )
		nocollide = constraint.NoCollide( cannon, trace.Entity, 0, trace.PhysicsBone )
		trace.Entity:DeleteOnRemove( cannon )
	end


	undo.Create("forcedynamite")
		undo.AddEntity( cannon )
		undo.AddEntity( const )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()
	
	ply:AddCleanup( "forcedynamite", cannon )
	ply:AddCleanup( "forcedynamite", const )
	ply:AddCleanup( "forcedynamite", nocollide )
	
	--Msg("Done")
	
	return true
	
end

function TOOL:RightClick( trace )
 	return false
end

if SERVER then

	--local Cannons = {}

	function MakeFDynamite(pl, Pos, Ang, key, force, model, recoil, reload, bangradius, effect, explodeoncontact, Vel, aVel, frozen )

		local cannon = ents.Create( "gmod_forcedynamite" )
			cannon:SetPos( Pos )	
			cannon:SetAngles( Ang )
			cannon:GetTable():Setup( force, model, recoil, reload, bangradius, effect, explodeoncontact)
			
			--make it shiny black
			
		cannon:Spawn()
		

		cannon:GetTable():SetPlayer( pl )

		numpad.OnDown( 	 pl, 	key, 	"ForceDynamite_On", 	cannon )
		numpad.OnUp( 	 pl, 	key, 	"ForceDynamite_Off", 	cannon )
		
		local ttable =
		{
			key			= key,
			force 		= force,
			model 		= model,
			pl			= pl,
			recoil 	= recoil,
			reload		= reload,
			bangradius=bangradius,
			effect=effect,
			explodeoncontact=explodeoncontact
		}

		table.Merge( cannon:GetTable(), ttable )
		
		
		pl:AddCount( "forcedynamite", cannon )
		--pl:AddCleanup( "propcannons", cannon )
		return cannon
		
	end
	
	duplicator.RegisterEntityClass( "gmod_forcedynamite", MakeFDynamite, "Pos", "Ang", "key", "force", "model", "recoil", "reload", "bangradius","effect","explodeoncontact", "Vel", "aVel", "frozen" )
	
end

function TOOL:UpdateGhost( ent, player )

	if ( !ent ) then return end
	if ( !ent:IsValid() ) then return end

	local tr 	= utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
	local trace 	= util.TraceLine( tr )
	
	if (!trace.Hit || trace.Entity:IsPlayer()||(trace.Entity && trace.Entity:GetClass() == "gmod_forcecannon") ) then
		ent:SetNoDraw( true )
		return
	end
	
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	ent:SetAngles( Ang )	

	local min = ent:OBBMins()
	ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
	
	ent:SetNoDraw( false )

end

function TOOL:Think()

	if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self:GetClientInfo( "model" ) ) then
		self:MakeGhostEntity( self:GetClientInfo( "model" ), Vector(0,0,0), Angle(0,0,0) )
	end
	
	self:UpdateGhost( self.GhostEntity, self:GetOwner() )
	
end

function TOOL.BuildCPanel(cp)

    cp:AddControl( "Header", { Text = "#Tool_forcedynamite_name", Description	= "#Tool_forcedynamite_desc" }  )

    local Combo = {}
	Combo["Label"] = "#Presets"
	Combo["MenuButton"] = "1"
	Combo["Folder"] = "propcannon"
	Combo["Options"] = {}
	Combo["Options"]["Default"] = {}
	Combo["Options"]["Default"]["forcedynamite_model"] = "models/dav0r/tnt/tnt.mdl"
	Combo["Options"]["Default"]["forcedynamite_force"] = "5000"
	Combo["Options"]["Default"]["forcedynamite_group"] = "1"
	Combo["Options"]["Default"]["forcedynamite_reload"] = "3"
	Combo["Options"]["Default"]["forcedynamite_recoil"] = "1"
	Combo["Options"]["Default"]["forcedynamite_bangradius"] = "256"
	Combo["Options"]["Default"]["forcedynamite_effect"] = "Explosion"
	Combo["Options"]["Default"]["forcedynamite_explodeoncontact"] = "0"
	Combo["CVars"] = {}
	Combo["CVars"]["0"] = "forcedynamite_model"
	Combo["CVars"]["1"] = "forcedynamite_force"
	Combo["CVars"]["2"] = "forcedynamite_group"
	Combo["CVars"]["3"] = "forcedynamite_reload"
	Combo["CVars"]["4"] = "forcedynamite_recoil"
	Combo["CVars"]["5"] = "forcedynamite_bangradius"
	Combo["CVars"]["6"] = "forcedynamite_effect"
	Combo["CVars"]["7"] = "forcedynamite_explodeoncontact"
	
	cp:AddControl("ComboBox", Combo )


    cp:AddControl( "Numpad", { Label = "Keypad button:", Command = "forcedynamite_group", Buttonsize = "22" } )
    cp:AddControl( "Slider", { Label = "Force:", Description = "How much force the dynamite fires with",Type = "float", Min = "-100000", Max = "100000", Command = "forcedynamite_force" } )
    cp:AddControl( "Slider", { Label = "Reload:", Description = "How long it takes before the dynamite can fire again", Type = "float", Min = "0", Max = "50", Command = "forcedynamite_reload" } )
    cp:AddControl( "Slider", { Label = "Recoil:", Description = "How much recoil the dynamite will produce",Type = "float", Min = "-10", Max = "10", Command = "forcedynamite_recoil" } )
    cp:AddControl( "Slider", { Label = "Explosive Radius:", Description = "The radius of any explosion",Type = "float", Min = "0", Max = "500", Command = "forcedynamite_bangradius" } )
    cp:AddControl( "Checkbox", { Label = "Explode on contact:", Description = "Should forced projectiles explode when they hit something", Command = "forcedynamite_explodeoncontact" } )
    
    local ComboModel = {}
	ComboModel["Label"] = "Force Dynamite model:"
	ComboModel["Options"] = {}
	ComboModel["Options"]["TNT"] = {}
	ComboModel["Options"]["TNT"]["forcedynamite_model"] = "models/dav0r/tnt/tnt.mdl"
	--ComboModel["Options"]["Crate"] = {}
	--ComboModel["Options"]["Crate"]["propcannon_model"] = "models/props_junk/wood_crate001a.mdl"
	ComboModel["Options"]["Bucket"] = {}
	ComboModel["Options"]["Bucket"]["forcedynamite_model"] = "models/props_junk/MetalBucket01a.mdl"
	ComboModel["Options"]["Trashcan"] = {}
	ComboModel["Options"]["Trashcan"]["forcedynamite_model"] = "models/props_trainstation/trashcan_indoor001b.mdl"
	ComboModel["Options"]["Traffic Cone"] = {}
	ComboModel["Options"]["Traffic Cone"]["forcedynamite_model"] = "models/props_junk/TrafficCone001a.mdl"
	ComboModel["Options"]["Oil Drum"] = {}
	ComboModel["Options"]["Oil Drum"]["forcedynamite_model"] = "models/props_c17/oildrum001.mdl"
	ComboModel["Options"]["Canister"] = {}
	ComboModel["Options"]["Canister"]["forcedynamite_model"] = "models/props_c17/canister01a.mdl"
	ComboModel["CVars"] = {}
	ComboModel["CVars"]["0"] = "forcedynamite_model"
	ComboModel["Command"] ="forcedynamite_model"
	
	cp:AddControl("ComboBox", ComboModel )

	local ComboEffect = {}
	ComboEffect["Label"] = "Fire effect:"
	ComboEffect["Options"] = {}
	ComboEffect["Options"]["Explosion"] = {}
	ComboEffect["Options"]["Explosion"]["forcedynamite_effect"] = "Explosion"
	ComboEffect["Options"]["Sparks"] = {}
	ComboEffect["Options"]["Sparks"]["forcedynamite_effect"] = "cball_explode"
	ComboEffect["Options"]["Bomb drop"] = {}
	ComboEffect["Options"]["Bomb drop"]["forcedynamite_effect"] = "RPGShotDown"
	ComboEffect["Options"]["Flash"] = {}
	ComboEffect["Options"]["Flash"]["forcedynamite_effect"] = "HelicopterMegaBomb"
	ComboEffect["Options"]["Machine Gun"] = {}
	ComboEffect["Options"]["Machine Gun"]["forcedynamite_effect"] = "HelicopterImpact"
	ComboEffect["Options"]["None"] = {}
	ComboEffect["Options"]["None"]["forcedynamite_effect"] = "none"
	

	ComboEffect["CVars"] = {}
	ComboEffect["CVars"]["0"] = "forcedynamite_effect"
	ComboModel["Command"] ="forcedynamite_effect"
	
	cp:AddControl("ComboBox", ComboEffect )


end
